package com.zqxq.lottery.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.common.utils.ValidateUtils;
import com.zqxq.lottery.entity.bo.user.UserInfoCMSBO;
import com.zqxq.lottery.entity.po.user.*;
import com.zqxq.lottery.entity.vo.user.*;
import com.zqxq.lottery.service.order.IUserOrderService;
import com.zqxq.lottery.service.user.*;
import com.zqxq.lottery.util.CardUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@RestController
@Slf4j
@RequestMapping("/userInfo")
public class UserInfoController extends UserBaseController{

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserBcardService userBcardService;
    @Autowired
    private IUserFundsService userFundsService;
    @Autowired
    private IUserPrizeService userPrizeService;
    @Autowired
    private IUserAlipayService userAlipayService;
    @Autowired
    private IUserOrderService userOrderService;
    @Autowired
    private IUserProductService userProductService;

    @ApiOperation("获取分页信息")
    @PostMapping("/queryPageList")
    public Result<Page<UserInfoCMSVO>> queryPageList(@RequestBody UserInfoCMSBO bo){
        Result<Page<UserInfoCMSVO>> result = new Result<>();
        try {
            Page<UserInfoCMSVO> page = userInfoService.queryPageList(bo);
            result.setData(page);
        }catch (Exception e) {
            log.error("userInfo queryPageList is error!", e);
        }
        return result;
    }
    @ApiOperation("获取详情")
    @PostMapping("/getCMSVO")
    public Result<UserInfoCMSVO> getCMSVO(Long userId,Integer pageNo,Integer pageSize){
        Result<UserInfoCMSVO> result = new Result<>();
        if (userId == null){
            return new Result(CodeEnum.FAIL_100002.getCode(),"userId不能为空");
        }
        try {
            UserInfoCMSVO userInfoCMSVO = userInfoService.getCmsVO(userId);
            if(userInfoCMSVO == null){
                userInfoCMSVO = new UserInfoCMSVO();
            } else {
                //兑奖列表
                List<UserProductListVO> list = userProductService.query(userId);
                userInfoCMSVO.setAwardList(list);
            }
            result.setData(userInfoCMSVO);
        } catch (Exception e) {
            log.error("userInfo UserInfoCMSVO is error!", e);
        }

        return result;
    }

    @ApiOperation("保存用户信息")
    @PostMapping("/save")
    public Result save(@RequestBody UserInfoVO vo){
        Result result = new Result();
        if(vo == null || StrUtils.isEmpty(vo.getUserId()) || StrUtils.isEmpty(vo.getMobile())){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            Wrapper wrapperEquipment = new EntityWrapper();
            wrapperEquipment.eq("equipment_id",vo.getEquipmentId());
            Integer count = userInfoService.selectCount(wrapperEquipment);
            if(count>3){
                return new Result(10000,"抱歉，一个手机最多支持3个账号登陆注册！");
            }
            userInfoService.saveUserInfo(vo);
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("mobile",vo.getMobile());
            List<UserInfoPO> userInfoPOList = userInfoService.selectList(wrapper);
            if(userInfoPOList!=null && userInfoPOList.size()!=0){
                UserInfoPO userInfoPO = userInfoPOList.get(0);
                Integer enabled = userInfoPO.getEnabled();
                if(enabled==1){
                    return new Result(10000,"抱歉，您的账户已被禁用！");
                }
            }
        } catch (Exception e) {
            log.error("userInfo save is error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }

        return result;
    }

    @ApiOperation("获取用户信息-该接口只能APP端用")
    @PostMapping("/get")
    public Result<UserInfoVO> get(Long userId){
        Result<UserInfoVO> result = new Result<>();
        try {
            UserInfoVO userInfoVO = userInfoService.getVO(userId);
            if(userInfoVO == null){
                userInfoVO = new UserInfoVO();
            }
            result.setData(userInfoVO);
        } catch (Exception e) {
            log.error("userInfo UserInfoCMSVO is error!", e);
        }
        return result;
    }
    @ApiOperation("判断手机号是否已经注册")
    @PostMapping("/getUserInfoByMobile")
    public Result<Integer> getUserInfoByMobile(String mobile){
        Result<Integer> result = new Result<>();
        try {
            Integer count = userInfoService.getUserInfoByMobile(mobile);
            result.setData(count);
        } catch (Exception e) {
            log.error("getUserInfoByMobile is error!", e);
        }
        return result;
    }

    @ApiOperation("根据手机号查询用户信息")
    @PostMapping("/getUserByMobile")
    public Result<UserInfoVO> getUserByMobile(String mobile){
        Result<UserInfoVO> result = new Result<>();
        try {
            UserInfoVO userInfoVO = userInfoService.getUserByMobile(mobile);
            result.setData(userInfoVO);
        } catch (Exception e) {
            log.error("getUserByMobile is error!", e);
        }
        return result;
    }

    @ApiOperation("实名认证")
    @PostMapping("/realAuth")
    public Result realAuth(Long userId, String realName, String idCard){
        Result result = new Result<>();
        if(userId == null || StrUtils.isEmpty(realName) || StrUtils.isEmpty(idCard)){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            Integer sex = CardUtil.getGenderByIdCard(idCard);
            int age= CardUtil.getAgeByIdCard(idCard);
            UserInfoPO userInfoPO = new UserInfoPO();
            userInfoPO.setId(userId);
            userInfoPO.setReal_name(realName);
            userInfoPO.setId_card(idCard);
            userInfoPO.setSex(sex);
            userInfoPO.setAge(age);
            userInfoService.realAuth(userInfoPO);
        } catch (Exception e) {
            log.error("userInfo UserInfoCMSVO is error!", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }

    @ApiOperation("设置支付密码")
    @PostMapping("/updatePayPassword")
    public Result updatePayPassword(Long userId, String payPassword){
        Result result = new Result();
        if(userId == null || StrUtils.isEmpty(payPassword)){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            userInfoService.updatePayPassword(userId, payPassword);
        } catch (Exception e) {
            log.error("userInfo save is error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }

        return result;
    }


    @ApiOperation("新增代理商账户")
    @PostMapping("/agent/addUserAgent")
    public Result addUserAgent(String mobile,String agentId){
        Result result = new Result();
        if(mobile == null || StrUtils.isEmpty(mobile)){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("mobile",mobile);
            List<UserInfoPO> userInfoPOList = userInfoService.selectList(wrapper);
            if(userInfoPOList!=null && userInfoPOList.size()>0){
                UserInfoPO userInfoPO = userInfoPOList.get(0);
                if(ValidateUtils.isEmpty(userInfoPO.getReal_name())){
                    new Result(10001,"该用户没有实名认证，请实名认证！");
                }
                userInfoService.addUserAgent(userInfoPO,agentId);
            }else{
                new Result(10001,"该手机号对应的用户不存在！");
            }
        } catch (Exception e) {
            log.error("userAgent save is error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }
    @ApiOperation("删除代理商账户")
    @PostMapping("/agent/deleteUserAgent")
    public Result deleteUserAgent(Long userId,Integer status){
        Result result = new Result();
        if(userId == null){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("id",userId);
            List<UserInfoPO> userInfoPOList = userInfoService.selectList(wrapper);
            if(userInfoPOList!=null && userInfoPOList.size()>0){
                userInfoService.deleteUserAgent(userId,status);
            }else{
                new Result(10001,"该用户不存在！");
            }
        } catch (Exception e) {
            log.error("userAgent delete is error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }

    /**
    * @Author 苦智
    * @Description
    * @Date 17:39 2018/7/7
    * @Param [agentId, timeType, month] 代理商id, 时间类型 1：月份 2：天, 月份
    * @return com.zqxq.common.constant.Result
    **/
    @PostMapping("/queryAgentDataById")
    public Result queryAgentDataById(String agentId,Integer timeType,String month,Integer pageNo,Integer pageSize ){
        if (agentId == null){
            return new Result(CodeEnum.FAIL_100002.getCode(),CodeEnum.FAIL_100002.getMsg());
        }
        if (pageNo == null)
            pageNo = 1;
        if (pageSize == null)
            pageSize = 10;
        Map<String,Object> resultMap = userInfoService.queryAgentDataById(agentId,timeType,month,pageNo,pageSize);
        return new Result(CodeEnum.SUCCESS.getCode(),CodeEnum.SUCCESS.getMsg(),resultMap);
    }
    @PostMapping("/sendCoupons")
    public Result sendCoupons(String mobiles,Long couponId){
        Result result = new Result();
        if(mobiles == null || StrUtils.isEmpty(mobiles) || couponId == null){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            userInfoService.sendCoupons(mobiles,couponId);
        } catch (Exception e) {
            log.error("sendCoupons error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }
    @PostMapping("/closureOrRelease")
    public Result closureOrRelease(Long userId,Integer enabled){
        Result result = new Result();
        if(userId == null || enabled == null){
            return new Result<>(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try {
            userInfoService.closureOrRelease(userId,enabled);
        } catch (Exception e) {
            log.error("closureOrRelease error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }
    @ApiOperation("修改个人信息")
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(Long userId, String headAddress,String nickName){
        Result result = new Result();
        try {
            userInfoService.updateUserInfo(userId, headAddress,nickName);
            result.setData(userId);
        } catch (Exception e) {
            log.error("userInfo save is error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }

    @ApiOperation("钻石兑换")
    @PostMapping("/exchangeDiamonds")
    public Result exchangeDiamonds(Long userId, BigDecimal payAmount){
        Result result = new Result();
        try {
            result = userFundsService.exchangeDiamonds(userId, payAmount);
        } catch (Exception e) {
            log.error("exchangeDiamonds is error", e);
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }

    @PostMapping("/excelBatchExport")
    public Result<List<UserInfoCMSVO>> excelBatchExport(@RequestBody UserInfoCMSBO bo){
        Result<List<UserInfoCMSVO>> rs = new Result();
        try{
            List<UserInfoCMSVO> list = userInfoService.query(bo);
            rs.setData(list);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UserInfo Query  Error:",e);
        }
        return rs;
    }

    @ApiOperation("任务中心")
    @PostMapping("/taskCenter")
    public Result taskCenter(Long userId){
        Result result = new Result();
        try {
            Map<String,Object> map = userInfoService.taskCenter(userId);
            result.setData(map);
        } catch (Exception e) {
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }

    @ApiOperation("邀请好友数据")
    @PostMapping("/inviteUsersData")
    public Result inviteUsersData(Long userId){
        Result result = new Result();
        try {
            Map<String,Object> map = userInfoService.inviteUsersData(userId);
            result.setData(map);
        } catch (Exception e) {
            result.setCode(CodeEnum.FAIL_100005.getCode());
            result.setMsg(CodeEnum.FAIL_100005.getMsg());
        }
        return result;
    }
}
